﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace EbbinghausWord.BLL
{
    /// <summary>
    /// 成绩管理
    /// </summary>
    public class ScoreManager
    {
        #region private field

        private static readonly IsolatedStorageFile _isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication();

        /// <summary>
        /// 成绩文件存储
        /// </summary>
        private static List<ScoreEntity> _scoreEntities = new List<ScoreEntity>();

        #endregion

        #region public method
        /// <summary>
        /// 保存成绩，将成绩文件加载到内存中，并进行成绩的初始化操作
        /// </summary>
        public static void InitScore()
        {
            //成绩文件是否存在
            if (!IsScoreFileExist())
            {
                //内存中实例化学习历史,设置昨日分数为0
                _scoreEntities.Add(new ScoreEntity()
                {
                    Date = DateTime.Now.AddDays(-1).ToEWDateFormat(),
                    Score = "0",
                });
            }
            else
            {
                //将文件加载到内存中
                LoadScore();
            }

            //是否有今日的成绩
            if (IsExistTodayScore())
            {
                //更新今日成绩
                UpdateTodayScore();
            }
            else
            {
                //寻找之前的成绩，在之前成绩与当前成绩之间做一次记录
                SetNewScore();
            }

            //保存成绩文件
            SaveScoreFile();

        }

        /// <summary>
        /// 获得当前得分
        /// </summary>
        /// <returns></returns>
        public static string GetCurrentScore()
        {
            //获得各个阶段的数量，计算总分
            double tmp = 0;

            var g1 = WordBookManager.GetWordsInWordbook().GroupBy(x => x.RememberLevel).ToList();
            var g2 = g1.Select((g, c) => new { Key = g.Key, Count = g.Count() }).ToList();
            var sl = g2.Select(g => SystemConfig.ScoreRatio[g.Key] * g.Count).ToList();

            return (sl.Sum() * SystemConfig.TotalScore / WordBookManager.WordBook.Count).ToString("0.000");
        }


        /// <summary>
        /// 将当前成绩从内存保存到磁盘上
        /// </summary>
        public static void SaveScoreFile()
        {
            using (var streamWriter = new StreamWriter(_isolatedStorageFile.OpenFile(SystemConfig.ScoreFileName,
                FileMode.Create, FileAccess.ReadWrite)))
            {

                var sb = new StringBuilder();
                foreach (var t in _scoreEntities)
                {
                    sb.AppendLine(t.ToString());
                }
                streamWriter.Write(sb.ToString());
            }
        }

        /// <summary>
        /// 成绩列表
        /// </summary>
        public static List<ScoreEntity> Scores { get { return _scoreEntities; } }

        #endregion

        #region private method

        /// <summary>
        /// 成绩文件是否存在
        /// </summary>
        /// <returns></returns>
        private static bool IsScoreFileExist()
        {
            return _isolatedStorageFile.FileExists(SystemConfig.ScoreFileName);
        }

        /// <summary>
        /// 更新今日成绩
        /// </summary>
        public static void UpdateTodayScore()
        {
            _scoreEntities.First(x => x.Date == DateTime.Now.ToEWDateFormat()).Score
                = GetCurrentScore();
        }

        /// <summary>
        /// 设置新的成绩
        /// </summary>
        private static void SetNewScore()
        {
            //找到目前最新成绩
            var newScore = _scoreEntities.OrderByDescending(x => x.Date).ToList()[0];

            //最新成绩设置为当前成绩
            newScore.Score = GetCurrentScore();

            //加入今日成绩
            _scoreEntities.Add(new ScoreEntity()
                                   {
                                       Date = DateTime.Now.ToEWDateFormat(),
                                       Score = GetCurrentScore(),
                                   });
        }

        /// <summary>
        /// 加载成绩到内存中
        /// </summary>
        private static void LoadScore()
        {
            _scoreEntities = new List<ScoreEntity>();

            using (var sr = new StreamReader(_isolatedStorageFile.OpenFile(SystemConfig.ScoreFileName,
              FileMode.OpenOrCreate)))
            {
                while (true)
                {
                    var scoreStr = sr.ReadLine();
                    if (string.IsNullOrEmpty(scoreStr)) break;

                    _scoreEntities.Add(ScoreEntity.CreateByString(scoreStr));
                }
            }
        }

        /// <summary>
        /// 是否存在今日成绩
        /// </summary>
        /// <returns></returns>
        private static bool IsExistTodayScore()
        {
            return _scoreEntities.Count(x => x.Date == DateTime.Now.ToEWDateFormat()) != 0;
        }

        #endregion
    }

    /// <summary>
    /// 成绩实体类
    /// </summary>
    public class ScoreEntity
    {
        public string Date { get; set; }
        public string Score { get; set; }

        /// <summary>
        /// 从字符串生成 成绩实体类
        /// </summary>
        /// <param name="scoreString"></param>
        /// <returns></returns>
        public static ScoreEntity CreateByString(string scoreString)
        {
            var scores = scoreString.Split(',');

            return new ScoreEntity()
                       {
                           Date = scores[0],
                           Score = scores[1],
                       };
        }

        /// <summary>
        /// 生成成绩文件的字符串，格式为2011-1-1,196.201
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return string.Format("{0},{1:0.000}", Date, Score);

        }
    }
}
